<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>录音</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    html,
    body {
      height: 100%;
    }

    body {
      display: flex;
      flex-direction: column;
    }

    .box1,
    .box2 {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    #record-btn {
      font-size: 2rem;
      padding: 0.6rem 1.2rem;
      user-select: none;
    }
  </style>
</head>

<body>
  <div class="box1">
    <audio id="audio-playback" controls disabled></audio>
    <a id="download-link" style="display:none;">下载录音</a>
  </div>
  <div class="box2">
    <button id="record-btn">点击录音</button>
  </div>
  <script>
    let mediaRecorder;
    let audioChunks = [];

    if (navigator.mediaDevices.getUserMedia) {
      const constraints = { audio: true };
      navigator.mediaDevices.getUserMedia(constraints).then(
        stream => {
          alert("授权成功！");

          mediaRecorder = new MediaRecorder(stream);

          mediaRecorder.ondataavailable = event => {
            audioChunks.push(event.data);
          };

          mediaRecorder.onstop = () => {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            const audioUrl = URL.createObjectURL(audioBlob);
            audioPlayback.src = audioUrl;

            downloadLink.href = audioUrl;
            downloadLink.download = 'recording.wav';
            downloadLink.style.display = 'block';

            audioChunks = [];
          };
        },
        () => {
          alert("授权失败！");
        }
      );
    } else {
      alert("当前浏览器不支持 getUserMedia");
    }

    const recordBtn = document.getElementById('record-btn');
    const audioPlayback = document.getElementById('audio-playback');
    const downloadLink = document.getElementById('download-link');

    function press(e) {
      e.preventDefault();
      if (mediaRecorder && mediaRecorder.state === 'inactive') {
        audioChunks = [];
        mediaRecorder.start();
        recordBtn.textContent = '录音中...';
        recordBtn.classList.add('recording');
        audioPlayback.src = '';
        downloadLink.style.display = 'none';
      } else if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
        recordBtn.textContent = '按下录音';
        recordBtn.classList.remove('recording');
      }
    }

    recordBtn.addEventListener('click', press);
  </script>
</body>

</html>